package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.BaiduUtil;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websoket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    AddressBookMapper addressBookMapper;
    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    BaiduUtil baiduUtil;
    @Autowired
    WebSocketServer webSocketServer;
    /*
    用户下单
     */

    @Override
    @Transactional
    public OrderSubmitVO submitOder(OrdersSubmitDTO ordersSubmitDTO) {
        //处理业务异常 地址问题 订单是否为空
        //判断订单是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());

        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        Long currentId = BaseContext.getCurrentId();
        User user = userMapper.getByid(currentId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(ShoppingCart.builder().userId(currentId).build());
        if (shoppingCartList.size() == 0) {
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向用户订单添加一条数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(currentId);
        orders.setUserName(user.getName());
        orderMapper.insert(orders);
        //向用户订单明显添加n条数据
        List<OrderDetail> list = new ArrayList<>();
        OrderDetail orderDetail = new OrderDetail();
        for (ShoppingCart cart : shoppingCartList) {
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);
        }
        orderDetailMapper.insert(list);
        //清空用户订单数据
        shoppingCartMapper.clean(ShoppingCart.builder().userId(currentId).build());
        //返回Vo

        return OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getByid(userId);

   /*     //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );*/
        JSONObject jsonObject = new JSONObject();
        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setTimeStamp(String.valueOf(System.currentTimeMillis()));
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        Map map = new HashMap<>();
        map.put("type", 1);
        map.put("orderId", ordersDB.getId());
        map.put("content", "订单号" + outTradeNo);
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = Orders.builder().status(6).cancelReason(ordersCancelDTO.getCancelReason()).cancelTime(LocalDateTime.now()).id(ordersCancelDTO.getId()).build();
        orderMapper.update(orders);
    }

    /*
    实现订单分页查询功能
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<OrderVO> orderVOList = new ArrayList<>();
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> ordersList = ordersPage.getResult();
        List<Long> listOrderId = new ArrayList<>();
        ordersList.forEach(orders -> {
            listOrderId.add(orders.getId());
        });
        if (listOrderId.size() > 0) {
            List<OrderDetail> orderDetail = orderMapper.detailPageQuery(listOrderId);
            StringBuffer orderString = new StringBuffer();
            for (Orders orders : ordersPage) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVOList.add(orderVO);
            }
            orderVOList.forEach(orderVO -> {
                List<OrderDetail> details = new ArrayList<>();
                for (OrderDetail detail : orderDetail) {
                    if (detail.getOrderId() == orderVO.getId()) {
                        details.add(detail);
                        orderString.append(detail.getName());
                    }
                }
                orderVO.setOrderDishes(orderString.toString());
                orderVO.setOrderDetailList(details);
            });
            return new PageResult(ordersPage.getTotal(), orderVOList);
        } else {
            return null;
        }
    }

    /*
    统计订单量
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = orderMapper.statistics();
        return orderStatisticsVO;
    }

    /*
    订单送单
     */
    @Override
    public void delivery(Long id) {

        Orders orders = Orders.builder().status(4).id(id).build();
        orderMapper.update(orders);
    }

    /*
    接受订单
     */
    @Override
    public void confirm(Long id) {
        Orders orders = orderMapper.getById(id);
       /*
       判断订单状态
        */
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException("订单状态错误");
        }
        /*
        判断订单是否超距
         */
        checkOutOfRange(orders.getAddress());

        orders = Orders.builder().status(3).id(id).build();
        orderMapper.update(orders);
    }

    /*
    拒绝送单
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {


        Orders orders = Orders.builder().status(6).rejectionReason(ordersRejectionDTO.getRejectionReason()).id(ordersRejectionDTO.getId()).build();
        orderMapper.update(orders);
    }

    /*
      完成送单
       */
    @Override
    public void complete(Long id) {
        Orders orders = orderMapper.getById(id);
       /*
       判断订单状态
        */
        if (orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException("订单状态错误");
        }
        orders = Orders.builder().status(5).deliveryTime(LocalDateTime.now()).id(id).build();
        orderMapper.update(orders);
    }

    /*
         查看订单详细
          */
    @Override
    public OrderVO details(Long id) {
        OrderVO orderVO = new OrderVO();
        //获得菜品详细信息数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getById(id);
        orderVO.setOrderDetailList(orderDetailList);
        // 获得菜品信息
        Orders orders = orderMapper.getById(id);
        BeanUtils.copyProperties(orders, orderVO);
        return orderVO;
    }

    /**
     * 查询历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        List<OrderVO> orderVOList = new ArrayList<>();
        Long currentId = BaseContext.getCurrentId();
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(currentId);
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);
        List<Orders> ordersList = ordersPage.getResult();
        List<Long> listOrderId = new ArrayList<>();
        ordersList.forEach(orders -> {
            listOrderId.add(orders.getId());
        });
        if (listOrderId.size() > 0) {
            List<OrderDetail> orderDetail = orderMapper.detailPageQuery(listOrderId);
            for (Orders orders : ordersPage) {
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVOList.add(orderVO);
            }
            orderVOList.forEach(orderVO -> {
                List<OrderDetail> details = new ArrayList<>();
                for (OrderDetail detail : orderDetail) {
                    if (detail.getOrderId() == orderVO.getId()) {
                        details.add(detail);
                    }
                }
                orderVO.setOrderDetailList(details);
            });
            return new PageResult(ordersPage.getTotal(), orderVOList);
        } else {
            return null;
        }
    }

    @Override
    public void remind(Long id) {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "订单号" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));


    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        String blocations = baiduUtil.getblocation();
        JSONObject jsonObject = JSON.parseObject(blocations);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;
        Map<String, String> map = new HashMap<>();
        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String ulocations = baiduUtil.getulocation(map);

        jsonObject = JSON.parseObject(ulocations);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = baiduUtil.getdistance(map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
//订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消 7退款